import { messages } from "share/common";
import React from 'react';
import { connect } from 'react-redux';
import errorMessage from 'share/errorMessage';
import menuRoute from 'routes/menuRoute'
import { message, Button, Popconfirm, Icon, Form, Input, Switch, Row, Col, Radio, TimePicker } from 'antd';
import ResizeTable from 'components/resize-table'
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
import moment from 'moment';
import Searcher from 'components/searcher'
import travelPolicyService from 'containers/expense-reimbursement-control/expense-standard/travel-policy/travel-policy.service'
import Priority from 'components/template/priority'
import CompactInput from 'components/compact-input'
import AllocationForm from 'containers/travel-standard/comp/form'
import BaseService from 'share/base.service';

class NewScene extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      setOfBooksId: '', //所属组织上的帐套
      permissionTop: 'SET_OF_BOOK', //SET_OF_BOOK帐套级权限 COMPANY 公司级权限
      priorityValue: {}, //所属组织，启用公司控件value
      priorityRangeValue: {}, //所属组织控件的rangeValue，包含整个对象信息
      hasProcessDefaultPriority: false, //是否处理过所属组织的默认值
      durationType: 1, //可用时段类型
      startTime: moment('00:00', 'HH:mm'),
      endTime: moment('23:59', 'HH:mm'),
      formScopeValue: {
        range: 'ALL',
        value: []
      } //适用表单控件value
    };
  }

  componentWillMount() {
    const { record, currentMenuPermission } = this.props;
    this.initPriority(currentMenuPermission);
    if (record) {
      this.initData(record);
      this.initPriorityValue();
    }
  };

  initData = (record) => {
    this.setState({
      durationType: record.durationType,
      startTime: moment(record.startTime, 'HH:mm'),
      endTime: moment(record.endTime, 'HH:mm'),
      formScopeValue: record.visibleFormScope === 2 ? {range: 'PARTIAL', value: record.visibleForms || []} : {range: 'ALL', value: []}
    });
  };

  //初始化页面权限
  initPriority = (currentMenuPermission) => {
    let policyDTO = currentMenuPermission.currentMenuPermission && currentMenuPermission.currentMenuPermission.authPolicyCompDTO;
    if (policyDTO && policyDTO.setOfBooksIds && policyDTO.setOfBooksIds.length) {
      this.setState({permissionTop: 'SET_OF_BOOK'}, this.initDefaultPriority);
    } else {
      this.setState({permissionTop: 'COMPANY'}, this.initDefaultPriority);
    }
  };

  //新建用餐类型处理所属组织默认值
  initDefaultPriority = () => {
    const { permissionTop, hasProcessDefaultPriority } = this.state;
    const { record } = this.props;
    if (hasProcessDefaultPriority || record) {
      //只处理一次默认值，新建用餐类型的时候处理
      return;
    }

    BaseService.dealDefaultPriority(permissionTop).then(res => {
      this.setState(res);
    }).catch(error => {
      message.error(messages('common.error')/*哦呼，服务器出了点问题，请联系管理员或稍后再试:(*/);
    }).finally(() => {
      this.setState({hasProcessDefaultPriority: true});
    });
  };

  initPriorityValue = () => {
    const { record } = this.props;
    let setOfBooksId = '';
    let priorityValue = {
      levelCode: record.levelCode,
      levelOrgId: record.levelCode === 'SET_OF_BOOK' ? record.levelOrgId : record.companyOID,
      levelOrgName: record.levelName
    };
    let priorityRangeValue = {};
    if (record.levelCode === 'SET_OF_BOOK') {
      priorityRangeValue = {
        setOfBooksId: record.levelOrgId,
        setOfBooksName: record.levelName
      };
      setOfBooksId = record.levelOrgId;
    }
    if (record.levelCode === 'COMPANY') {
      priorityRangeValue = {
        id: record.levelOrgId,
        companyOID: record.companyOID,
        name: record.levelName
      };
    }
    this.setState({priorityValue, priorityRangeValue, setOfBooksId});
  };

  componentWillReceiveProps(nextProps) {};

  onCancel = () => {
    this.props.close();
  };

  handleSave = () => {
    const { form, close, record } = this.props;
    const { durationType, startTime, endTime, priorityValue, priorityRangeValue, formScopeValue } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (!priorityValue.levelOrgId) {
          message.error(messages('request-1.key723')/*请选择所属组织*/);
          return;
        }
        if (formScopeValue && formScopeValue.range === 'PARTIAL' && !formScopeValue.value.length) {
          message.error(messages('request-1.key762')/*请选择适用表单*/);
          return;
        }
        //需要校验startTime是否在endTime之前
        if (durationType === 2 && !moment(startTime).isBefore(endTime)) {
          message.error(messages('request-1.key763')/*开始时间需早于结束时间*/);
          return;
        }
        let params = {};
        params.levelCode = priorityValue.levelCode;
        params.levelOrgId = priorityValue.levelCode === 'SET_OF_BOOK' ? priorityValue.levelOrgId : priorityRangeValue.id;
        params.id = record ? record.id : undefined;
        params.name = values.name;
        params.status = values.enable ? 1 : 0;
        params.frequency = values.frequency;
        params.durationType = durationType;
        params.startTime = moment(startTime).format('HH:mm');
        params.endTime = moment(endTime).format('HH:mm');
        params.visibleFormScope = formScopeValue.value.length ? 2 : 1; //适用表单范围，1全部 2部分
        params.visibleForms = formScopeValue.value;
        this.setState({loading: true});
        travelPolicyService.saveDiningScene(params).then(res => {
          this.setState({loading: false});
          message.success(messages('common.save.success',{arg1: params.name})/*{arg1} 保存成功*/);
          close(true);
        }).catch(e => {
          this.setState({loading: false});
          errorMessage(e.response);
        });
      }
    });
  };

  handleChangeValue = (value, key) => {
    this.setState({[key]: value});
  };

  handleTimeChange = (time, type) => {
    if (type === 'start') {
      this.setState({startTime: time});
    }
    if (type === 'end') {
      this.setState({endTime: time});
    }
  };

  handleChangePriority = (value) => {
    const { priorityValue: oldPriorityValue } = this.state;
    if (value && value.levelCode === 'COMPANY' && value.levelOrgId !== oldPriorityValue.levelOrgId) {
      //所属组织为公司，切换公司时清空依赖数据
      this.clearDependency();
    }
    this.setState({priorityValue: value || {}});
  };

  handleChangePriorityRange = (value) => {
    const { setOfBooksId: oldSetOfBooksId } = this.state;
    if (!value) {
      //如果为空，清空依赖数据
      this.clearDependency();
      this.setState({setOfBooksId: ''});
    } else {
      let newSetOfBooksId = value.setOfBooksId;
      newSetOfBooksId !== oldSetOfBooksId && this.clearDependency();
      this.setState({setOfBooksId: newSetOfBooksId});
    }
    this.setState({priorityRangeValue: value});
  };

  //所属组织切换了账套或者切换了公司，清除依赖账套，公司查询的配置数据
  clearDependency = () => {
    let { formScopeValue } = this.state;
    formScopeValue.value = [];
    this.setState({formScopeValue});
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { loading, durationType, startTime, endTime, permissionTop, priorityValue, setOfBooksId, formScopeValue, hasProcessDefaultPriority } = this.state;
    const { record } = this.props;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 16}
    };
    return (
      <div className="new-form">
        <Form>
          <FormItem {...formItemLayout} label={messages('common.column.status')/*状态*/}>
            {getFieldDecorator('enable', {
              valuePropName: 'checked',
              initialValue: record ? record.status === 1 : true
            })(
              <Switch />
            )}
          </FormItem>
          {!(record && record.id) && hasProcessDefaultPriority && (
            <Priority
              top={permissionTop}
              onChange={this.handleChangePriority}
              formItemLayout={formItemLayout}
              onChangeRange={this.handleChangePriorityRange}
              companyProps={{
                valueKey: 'companyOID',
                single: true
              }}
              showCompanyComponent={false}
              defaultValue={priorityValue}
            />
          )}
          {record && record.id && (
            <FormItem {...formItemLayout} label={messages('request-1.key727')/*所属组织*/}>
              <CompactInput>
                <Input
                  disabled
                  value={priorityValue.levelCode === 'SET_OF_BOOK' ? messages('request-1.key743')/*帐套*/ : messages('request-1.key725')/*公司*/}
                />
                <Input
                  disabled
                  value={priorityValue.levelOrgName}
                />
              </CompactInput>
            </FormItem>
          )}
          <FormItem {...formItemLayout} label={messages('request-1.key746')/*适用表单*/}>
          <div className='normal-width'>
            <AllocationForm
              componentProps={{
                'PARTIAL': {
                  listExtraParams: {
                    setOfBooksId,
                    companyOID: priorityValue.levelCode === 'SET_OF_BOOK' ? undefined : priorityValue.levelOrgId,
                    formTypeList: [2001],
                    withSetOfBooks: false
                  }
                }
              }}
              parser={value => ({range: value.range, value: value.value || []})}
              value={formScopeValue}
              onChange={value => this.handleChangeValue(value, 'formScopeValue')}
              disabled={!priorityValue.levelOrgId}
            />
            </div>
          </FormItem>
          <div className="sub-title" style={{fontWeight: 'bolder', fontSize: '16px', marginBottom: '16px'}}>{messages('request-1.key764')/*类型设置*/}</div>
          <FormItem {...formItemLayout} label={messages('request-1.key765')/*类型名称*/}>
            {getFieldDecorator('name', {
              rules: [{
                required: true,
                message: messages('common.please.input')/*请输入*/
              }],
              initialValue: record ? record.name : ''
            })(
              <Input placeholder={messages('common.please.input')/*请输入*/} maxLength="10" />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('request-1.key766')/*可用时段*/}>
            <div>
              <RadioGroup value={durationType} onChange={e => this.handleChangeValue(e.target.value, 'durationType')}>
                <Radio value={1}>{messages('request-1.key378')/*全天*/}</Radio>
                <Radio style={{marginLeft: 50}} value={2}>{messages('request-1.key767')/*限制时段*/}</Radio>
              </RadioGroup>
              {durationType === 2 && (
                <div style={{marginTop: 12}}>
                  <TimePicker allowEmpty={false} value={startTime} format='HH:mm' onChange={time => this.handleTimeChange(time, 'start')} />
                  <TimePicker style={{marginLeft: 12}} allowEmpty={false} value={endTime} format='HH:mm' onChange={time => this.handleTimeChange(time, 'end')} />
                </div>
              )}
            </div>
          </FormItem>
          <FormItem {...formItemLayout} label={messages('request-1.key768')/*用餐频次*/}>
            {getFieldDecorator('frequency', {
              initialValue: record ? (record.frequency || 1001) : 1001
            })(
              <RadioGroup>
                <Radio value={1001}>{messages('request-1.key381')/*单次*/}</Radio>
                <Radio style={{marginLeft: 50}} value={1002}>{messages('request-1.key380')/*每天*/}</Radio>
              </RadioGroup>
            )}
          </FormItem>
        </Form>
        <div className="slide-footer">
          <Button type="primary" onClick={this.handleSave} loading={loading}>{messages('common.ok')/*确定*/}</Button>
          <Button onClick={this.onCancel}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    currentMenuPermission: state.main.currentMenuPermission
  }
}

NewScene.propTypes = {};

NewScene.defaultProps = {};

const WrappedNewScene = Form.create()(NewScene);

export default connect(mapStateToProps)(WrappedNewScene);
